package dbinit;

import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import core.attribute.model.Attribute;
import core.attribute.model.AttributeValue;
import core.util.HibernateCoreUtil;

public class InitAttribute 
{
	public static Attribute getAttributeByName(String name)
	{
		Attribute a = null;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			a = (Attribute) session.createCriteria(Attribute.class).add(Restrictions.eq("name", name)).uniqueResult();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return a ;
	}
	public static Attribute getAttributeByUuid(Long uuid)
	{
		Attribute a = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				a = (Attribute) session.get(Attribute.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return a ;
	}
	public static Long doinit(String name ,Set<AttributeValue> values,boolean multivalued)
	{
		Attribute a = getAttributeByName(name) ;
		Long uuid = null ;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			if(multivalued == true)
			{
				if(a == null)
				{
					a = new Attribute();
					a.setName(name);
					a.setValues(values);
					a.setMultivalued(multivalued);
					uuid = (Long) session.save(a);
				}
				else
				{
					a.setValues(values);
					uuid = a.getUuid();
					session.merge(a);
				}
			}
			else
			{
				if(a == null)
				{
					a = new Attribute();
					a.setName(name);
					a.setMultivalued(multivalued);
					uuid = (Long) session.save(a);
				}
				else
				{
					a.setMultivalued(multivalued);
					session.merge(a);
					uuid = a.getUuid();
				}
			}
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return uuid;
	}
	
}
